#!/usr/bin/python
# -*- coding: utf-8 -*-
import fnmatch
import gtk
icon_theme = gtk.icon_theme_get_default()

default_size = 22

match_mappings = {
    '*.r[0-9][0-9]': 'package',
    'README*': 'ascii',
}

ending_mappings = {
    'video': ['.avi', '.wmv', '.asf', '.ogm', '.mkv', '.mpg', '.mpeg'],
    'package': ['.rar', '.gz', '.deb', '.bz2'],
    'ascii': ['.sfv', '.nfo', '.md5', '.txt', '.cfg', '.py'],
    'image': ['.jpg', '.gif', '.png'],
    'sound': ['.mp3', '.flac', '.ogg'],
    'binary': ['.exe'],
}

cache = {}


def by_filename(filename, size=default_size):
    """Return a pixbuf of the best guess based on filename."""
    filename = filename.lower()
    
    # match_match_match lets go nuts.
    match_mapping_matches = [x for x in match_mappings.keys() if fnmatch.fnmatch(filename, x)]
    if match_mapping_matches:
        if icon_theme.has_icon(match_mappings[match_mapping_matches[0]]):
            return icon_theme.load_icon(match_mappings[match_mapping_matches[0]], size, 0)
    
    for key in ending_mappings:
        for ending in ending_mappings[key]:
            if filename.endswith(ending):
                return icon_theme.load_icon(key, size, 0)
        
    if len(filename) > 3 and filename[-4] == "." and icon_theme.has_icon(filename[-3:]):
        return icon_theme.load_icon(filename[-3:], size, 0)
    
    return None
    
    
def from_theme(i, size=None):
    """Return pixbuf of name."""
    if type('') == type(i):
        if not size: size = default_size
        if (i, size) in cache:
            return cache[(i, size)]
        else:
            pixbuf = icon_theme.load_icon(i, size, 0)
            cache[(i, size)] = pixbuf
            return pixbuf
    elif type(0) == type(i):
        if not size: size = gtk.ICON_SIZE_MENU
        return gtk.image_new_from_stock(i, size)
    else:
        raise TypeError, "Unknown type '%s' passed to from_theme()" % type(i)
    
    
def folder(open=False, size=default_size):
    """Return the icon for a folder."""
    s = 'folder%s' % (open and '-open' or '')
    
    if (s, size) in cache:
        return cache[(s, size)]
    else:
        pixbuf = icon_theme.load_icon(s, size, 0)
        cache[(s, size)] = pixbuf
        return pixbuf
    
